package com.base.cn.platform.os.common.interceptor.keyword;

import com.base.cn.platform.os.service.manage.op.keyword.OpKeywordService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 敏感词过滤
 *
 * @author s.li
 * @create 2018-09-20-11:11
 */
@Slf4j
public class KeyWordFilter implements Filter {
    private OpKeywordService opKeywordService;
    private StringBuilder context = new StringBuilder();
    private long time = System.currentTimeMillis();
    //过滤工具
    private SensitiveFilterService filter;

    public KeyWordFilter(OpKeywordService opKeywordService){
        this.opKeywordService = opKeywordService;
    }

    @Override
    public void init(FilterConfig filterConfig) {
        filter = SensitiveFilterService.getInstance();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long _time = System.currentTimeMillis();
        if(_time - time >= 10 * 1000 || context.length() == 0){//缓存30秒
            time = _time;
            String keyWordContext = opKeywordService.findAllKeyword();
            context.delete(0,context.length());
            context.append(keyWordContext);
        }
        KeyWebHttpServletRequestWrapper keyWordRequest = new KeyWebHttpServletRequestWrapper((HttpServletRequest) request,filter,context);
        chain.doFilter(keyWordRequest,response);
    }

    @Override
    public void destroy() {

    }
}
